package com.example.demo1.service.impl;

import com.example.demo1.model.Category;
import com.example.demo1.model.Drink;
import com.example.demo1.repository.CategoryRepository;
import com.example.demo1.repository.DrinkRepository;
import com.example.demo1.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service

public class CategoryJpaService implements ICategoryService {
    @Autowired
    public CategoryRepository categoryRepository;
    @Autowired
    public DrinkRepository drinkRepository;

    @Override
    public List<Category> getAllCategories() {

        return categoryRepository.findAll();
    }

    @Override
    public void addNewCategory(Category category) {
        categoryRepository.save(category);
    }

    @Override
    public Category getCategoryById(Integer id) {
        Optional<Category> optional = categoryRepository.findById(id);
        if (optional.isPresent()) {
            return optional.get();
        }
        return null;
    }

    @Override
    public void updateCategory(Category category) {
        categoryRepository.save(category);
    }

    @Override
    public void deleteCategoryById(Integer id) {
        //删除指定id

        //
        List<Drink> drinks = drinkRepository.findDrinksByCategory_Id(id);
        //
        for (Drink drink : drinks) {
            drink.setCategory(null);
            drinkRepository.save(drink);
        }
        categoryRepository.deleteById(id);
    }
}
